package com.yuncheng.spcyApi.controller;

import java.io.File;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.constant.common.BusinessConstant;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.constant.SysUserConstant;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.entity.YcSysUserDepart;
import com.yuncheng.entity.YcSysUserRole;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetUuIdUtils;
import com.yuncheng.spcyApi.utils.LocalFileUploadUtils;
import com.yuncheng.spcyApi.utils.MyExcelUtils;
import com.yuncheng.vo.HttpResult;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.entity.SpcyRsHcy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.vo.jcy.RsHcyMapVo;
import com.yuncheng.spcyApi.vo.jcy.RsHcyVo;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import utils.LogUtils;
import utils.ObjectToMapUtils;

@Api(tags = "审评查验-核查员库接口")
@RestController
@RequestMapping("/api/spzx-spcy/spcyRsHcy")
public class SpcyRsHcyController extends BaseController<SpcyRsHcy, ISpcyRsHcyService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyRsHcyController.class);

    @Resource
    private ISpcyRsHcyService spcyRsHcyService;

    /*@Resource
    private SpcyRsHcyMapper spcyRsHcyMapper;*/

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    private LocalFileUploadUtils localFileUploadUtils;

    @Resource
    private MyExcelUtils myExcelUtils;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private IYcSysUserService ycSysUserService;

    @Log(title = "审评查验-核查员库-分页列表查询")
    @ApiOperation(value = "审评查验-核查员库-分页列表查询")
    @GetMapping(value = "/list")
    public HttpResult<?> queryPageList(RsHcyVo spcyRsHcy, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                       @RequestParam(name = "pageSize", defaultValue = "100") Integer pageSize,
                                       @RequestParam(value = "orderItem",defaultValue = "")String orderItem,
                                       @RequestParam(value = "orderType",defaultValue = "asc")String orderType) {

        Page<RsHcyVo> page = new Page<>(pageNo, pageSize);
//        spcyRsHcy.setFstate(SpcyCommonConstant.JCY_STATE_YX); // 有效
        IPage<RsHcyVo> rsHcyListVoIPage = spcyRsHcyService.pageRsHcyList(page, spcyRsHcy,orderItem,orderType);
        return HttpResult.ok(rsHcyListVoIPage);
    }

    /*@Log(title = "核查员-重置密码")
    @ApiOperation(value = "核查员-重置密码")
    @ApiImplicitParam(name = "fuserid",value = "用户id",required = true)
    @GetMapping(value = "resetHcyPwd")*/
    public HttpResult<?> resetHcyPwd(@RequestParam("fuserid")String fuserid){
        if (StringUtils.isBlank(fuserid)){
            return HttpResult.error("用户主要参数丢失，请联系管理员");
        }
        YcSysUser user = ycSysUserService.getById(fuserid);
        if (user == null){
            return HttpResult.error("当前用户不存在，请刷新重试");
        }
        Map<String, Object> userMap = ObjectToMapUtils.objectToMap(user);

        user.setPassword(SysUserConstant.PASSWORD);
        user.setSalt(SysUserConstant.SALT);
        ycSysUserService.updateById(user);

        String lognr = "重置密码：";
        lognr += LogUtils.BeanModifyMsg(user,userMap);
        spcyLogService.addLogs("重置密码",lognr,fuserid,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XG);

        return HttpResult.ok("重置成功");
    }

    /*@Log(title = "核查员-修改账号")
    @ApiOperation(value = "核查员-修改账号")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true),
            @ApiImplicitParam(name = "username",value = "账号",required = true)
    })
    @PutMapping(value = "modifyHcyAccount")*/
    public HttpResult<?> modifyHcyAccount(@RequestBody Map<String,String> map){
        String fuserid = map.get("fuserid");
        String username = map.get("username");

        if (StringUtils.isBlank(fuserid)){
            return HttpResult.error("用户主要参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(username)){
            return HttpResult.error("账号不能为空");
        }
        YcSysUser user = ycSysUserService.getById(fuserid);
        if (user == null){
            return HttpResult.error("当前用户不存在，请联系管理员");
        }
        String oldUsename = user.getUsername();
        // 当前账号与当前用户账号相同
        if (oldUsename.equals(username)){
            return HttpResult.ok("修改成功");
        }
        // 是否存在该账号
        List<YcSysUser> zhList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>().eq(YcSysUser::getUsername, username));
        if (CollectionUtils.isNotEmpty(zhList)){
            return HttpResult.error("账号已经存在，请重新修改");
        }
        // 不存在修改账号
        if (CollectionUtils.isEmpty(zhList)){
            user.setUsername(username);
            ycSysUserService.updateById(user);

            String logNr = "修改账号: 【姓名】为["+user.getRealname()+"];【账号】从["+oldUsename+"]设置为["+username+"];";
            spcyLogService.addLogs("修改账号",logNr,fuserid,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XG);
        }

        return HttpResult.ok("修改成功");
    }

    /*@Log(title = "核查员-执勤状态修改")
    @ApiOperation(value = "核查员-执勤状态修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "fuserid",value = "用户id",required = true),
            @ApiImplicitParam(name = "fgzzt",value = "执勤状态",required = true)
    })
    @PutMapping(value = "modifyHcyGzzt")*/
    public HttpResult<?> modifyHcyGzzt(@RequestBody Map<String,String> map){
        String fuserid = map.get("fuserid");
        String fgzzt = map.get("fgzzt");
        if (StringUtils.isBlank(fuserid)){
            return HttpResult.error("用户主要参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(fgzzt)){
            return HttpResult.error("执勤状态不能为空");
        }
        YcSysUser user = ycSysUserService.getById(fuserid);
        if (user == null){
            return HttpResult.error("当前用户不存在，请联系管理员");
        }
        String oldGzzt = user.getFgzzt();
        user.setFgzzt(fgzzt);
        ycSysUserService.updateById(user);
        String logNr = "修改执勤状态: 【姓名】为["+user.getRealname()+"];【账号】从["+oldGzzt+"]设置为["+fgzzt+"];";
        spcyLogService.addLogs("修改执勤状态",logNr,fuserid,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XG);

        return HttpResult.ok("修改成功");
    }

    /*@Log(title = "核查员-所属库修改")
    @ApiOperation(value = "核查员-所属库修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "核查员id",required = true),
            @ApiImplicitParam(name = "fssk",value = "所属库",required = true)
    })
    @PutMapping(value = "modifyHcySsk")*/
    public HttpResult<?> modifyHcySsk(@RequestBody Map<String,String> map){
        String id = map.get("id");
        String fssk = map.get("fssk");
        if (StringUtils.isBlank(id)){
            return HttpResult.error("核查员主要参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(fssk)){
            return HttpResult.error("所属库不能为空");
        }
        SpcyRsHcy hcy = spcyRsHcyService.getById(id);
        if (hcy == null){
            return HttpResult.error("当前核查员不存在，请刷新重试");
        }
        YcSysUser user = ycSysUserService.getById(hcy.getFuserid());
        if (user == null){
            return HttpResult.error("当前用户不存在，请刷新重试");
        }
        String oldssk = hcy.getFssk();
        hcy.setFssk(fssk);
        spcyRsHcyService.updateById(hcy);

        String logNr = "修改所属库: 【姓名】为["+user.getRealname()+"];【所属库】从["+oldssk+"]设置为["+fssk+"];";
        spcyLogService.addLogs("修改所属库",logNr,id,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XG);

        return HttpResult.ok("修改成功");
    }

    /*@Log(title = "核查员-有效状态修改")
    @ApiOperation(value = "核查员-有效状态修改")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value = "核查员id",required = true),
            @ApiImplicitParam(name = "fstate",value = "有效状态",required = true)
    })
    @PutMapping(value = "modifyHcyState")*/
    public HttpResult<?> modifyHcyState(@RequestBody Map<String,String> map){
        String id = map.get("id");
        String fstate = map.get("fstate");
        if (StringUtils.isBlank(id)){
            return HttpResult.error("核查员主要参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(fstate)){
            return HttpResult.error("有效状态不能为空");
        }
        SpcyRsHcy hcy = spcyRsHcyService.getById(id);
        if (hcy == null){
            return HttpResult.error("当前核查员不存在，请刷新重试");
        }
        YcSysUser user = ycSysUserService.getById(hcy.getFuserid());
        if (user == null){
            return HttpResult.error("当前用户不存在，请刷新重试");
        }
        String oldState = hcy.getFstate();
        hcy.setFstate(fstate);
        spcyRsHcyService.updateById(hcy);

        String logNr = "修改有效状态: 【姓名】为["+user.getRealname()+"];【有效状态】从["+oldState+"]设置为["+fstate+"];";
        spcyLogService.addLogs("修改有效状态",logNr,id,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XG);

        return HttpResult.ok("修改成功");
    }

    /*@Log(title = "审评查验-核查员库-添加")
    @ApiOperation(value = "审评查验-核查员库-添加")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "fuserid",name = "用户id",required = true),
            @ApiImplicitParam(value = "id",name = "核查员id",required = true)
    })
    @PostMapping(value = "/add")*/
    public HttpResult<?> saveByAdmin(@RequestBody RsHcyMapVo rsHcyMapVo) throws InvocationTargetException, IllegalAccessException {
        //先拿到账号 ，校验是否需要新增yc用户
        //拿到业务编码和用户id 校验是否需要新增hcy用户
       /* YcSysUser ycSysUser = new YcSysUser();
        String userId = "";
        BeanUtil.copyProperties(rsHcyVo,ycSysUser);*/
        HashMap<String, String> userMap = rsHcyMapVo.getUserMap();
        HashMap<String, String> hcyMap = rsHcyMapVo.getHcyMap();

        if (StringUtils.isEmpty(userMap.get("username"))){
            return HttpResult.error("账号不能为空");
        }
        if (StringUtils.isEmpty(userMap.get("realname"))){
            return HttpResult.error("姓名不能为空");
        }
        if (StringUtils.isEmpty(hcyMap.get("fywflcode"))){
            return HttpResult.error("核查员所属业务分类不能为空");
        }
        String fywflcode = hcyMap.get("fywflcode");
        String username = userMap.get("username");
        String fusertype = hcyMap.get("fusertype");

        //处理用户信息保存
        String userId = "";
        userId = userMap.get("fuserid");
        // 用户id不为空
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotEmpty(userId)){
            //执行对用户的保存
            YcSysUser oldSysUser = ycSysUserService.getById(userId);
            YcSysUser ycSysUserUpdate = ycSysUserService.getById(userId);
            BeanUtils.populate(ycSysUserUpdate,userMap);
            ycSysUserService.updateById(ycSysUserUpdate);

            //加保存日志
            String editUser = "修改用户信息: ";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldSysUser);
            editUser += LogUtils.BeanModifyMsg(ycSysUserUpdate,oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER,editUser,userId,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XG);

        }else{
            // 查询账号
            List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                    .eq(YcSysUser::getUsername, username));
            if (CollectionUtils.isNotEmpty(userList)){
                return HttpResult.error("账号【"+username+"】已存在");
            }else{
                //新增用户
                YcSysUser ycSysUser = new YcSysUser();
                BeanUtils.populate(ycSysUser,userMap);
                userId = GetUuIdUtils.ReplaceUuId();
                ycSysUser.setId(userId);
                ycSysUser.setPassword(SysUserConstant.PASSWORD);
                ycSysUser.setSalt(SysUserConstant.SALT);
                ycSysUser.setWorkNo(userId);
                ycSysUser.setIsRealUser(SysUserConstant.IS_REAL_USER);
                ycSysUser.setStatus(Integer.valueOf(SysUserConstant.STATUS));
                ycSysUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG));
                // 判断核查员、专家
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    ycSysUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
                    ycSysUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
                    ycSysUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码
                }else {
                    ycSysUser.setOrgId(SpcyConstant.HCY_ZJ_ORGID); // 部门编号
                    ycSysUser.setOrgName(SpcyConstant.HCY_ZJ_ORGNAME); // 部门名称
                    ycSysUser.setOrgCode(SpcyConstant.HCY_ZJ_ORGCODE); // 默认机构编码
                }

                ycSysUserService.save(ycSysUser);

                // 新增日志
                String addSysUserOper = "新增用户：";
                Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(ycSysUser);
                addSysUserOper += LogUtils.MapToStringMethod(addUserMap);
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER,addSysUserOper,userId,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XZ);

                // 新增部门用户关系
                YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
                ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
                ycSysUserDepart.setUserId(userId);

                // 判断核查员、专家
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
                }else {
                    ycSysUserDepart.setDepId(SpcyConstant.HCY_ZJ_ORGID); // 专家部门编号
                }

                ycSysUserDepart.setPositionId(""); // 职务编号
                ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
                ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);

                // 用户部门 日志
                String ycAddUserDepartOperCont = "新增系统用户部门联系：用户名["+ycSysUser.getRealname()+"]; 部门["+SpcyConstant.HCY_ORGNAME+"]; " +
                        "用户编号["+userId+"]; 部门编号["+SpcyConstant.HCY_ORGID+"];";
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_DEPT,ycAddUserDepartOperCont,userId,LogConstant.LOGS_SYS_USER_DEPT,SpcyConstant.LOGS_SYS_TYPE_XZ);

                String roleId = "";
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    roleId = SpcyConstant.getRoleIdByCode(fywflcode);
                }else {
                    roleId = SpcyConstant.getZjRoleIdByCode(fywflcode);
                }

                // 对用户角色进行自动授权
                YcSysUserRole userRole = new YcSysUserRole();
                userRole.setId(GetUuIdUtils.ReplaceUuId());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                ycSysUserMapper.addYcSysUserRole(userRole);

                // 加新增和授权的日志
                String ycAddUserRoleOperCont = "新增用户角色联系：用户名["+ycSysUser.getRealname()+"]; 用户编号["+userId+"]; " +
                        "角色编号["+roleId+"];]";
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_ROLE,ycAddUserRoleOperCont,userId,LogConstant.LOGS_SYS_USER_ROLE,SpcyConstant.LOGS_SYS_TYPE_XZ);

            }

        }


        //处理核查员信息保存
        String hcyId = hcyMap.get("id");
        if(StringUtils.isNotBlank(hcyId) && StringUtils.isNotEmpty(hcyId)){
            //执行核查员信息更新
            SpcyRsHcy oldHcy = spcyRsHcyService.getById(hcyId);
            SpcyRsHcy hcyUpdate = spcyRsHcyService.getById(hcyId);
            BeanUtils.populate(hcyUpdate,hcyMap);
            spcyRsHcyService.updateById(hcyUpdate);

            //增加修改日志
            String editUser = "修改核查员信息: ";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldHcy);
            editUser += LogUtils.BeanModifyMsg(hcyUpdate,oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCY,editUser,userId,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XG);

        }else{
            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFuserid, userId)
                    .eq(SpcyRsHcy::getFywflcode, fywflcode)
            );
            if (CollectionUtils.isNotEmpty(hcyList)){
                return HttpResult.error("业务分类【"+fywflcode+"】+核查员【"+username+"】已存在");
            }else{
                SpcyRsHcy spcyRsHcy = new SpcyRsHcy();
                BeanUtils.populate(spcyRsHcy,hcyMap);
                spcyRsHcy.setId(GetUuIdUtils.ReplaceUuId());
                spcyRsHcy.setFuserid(userId);
                spcyRsHcyService.save(spcyRsHcy);

                //增加日志记录
                String addHcyOper = "新增核查员";
                Map<String, Object> addHcyMap = ObjectToMapUtils.objectToMap(spcyRsHcy);
                addHcyOper += LogUtils.MapToStringMethod(addHcyMap);
                spcyLogService.addLogs(LogConstant.LOGS_RS_HCY,addHcyOper,userId,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }


        return HttpResult.ok("操作成功");
    }

    /*@Log(title = "审评查验-核查员库-编辑")
    @ApiOperation(value = "审评查验-核查员库-编辑")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "fuserid",name = "用户id",required = true),
            @ApiImplicitParam(value = "id",name = "核查员id",required = true)
    })
    @PutMapping(value = "/edit")*/
    public HttpResult<?> edit(@RequestBody RsHcyMapVo rsHcyMapVo) throws InvocationTargetException, IllegalAccessException{
        HashMap<String, String> userMap = rsHcyMapVo.getUserMap();
        HashMap<String, String> hcyMap = rsHcyMapVo.getHcyMap();

        if (StringUtils.isEmpty(userMap.get("username"))){
            return HttpResult.error("账号不能为空");
        }
        if (StringUtils.isEmpty(userMap.get("realname"))){
            return HttpResult.error("姓名不能为空");
        }
        if (StringUtils.isEmpty(hcyMap.get("fywflcode"))){
            return HttpResult.error("核查员所属业务分类不能为空");
        }
        String fywflcode = hcyMap.get("fywflcode");
        String username = userMap.get("username");
        String fusertype = hcyMap.get("fusertype");

        //处理用户信息保存
        String userId = "";
        userId = userMap.get("fuserid");
        // 用户id不为空
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotEmpty(userId)){
            //执行对用户的保存
            YcSysUser oldSysUser = ycSysUserService.getById(userId);
            YcSysUser ycSysUserUpdate = ycSysUserService.getById(userId);
            BeanUtils.populate(ycSysUserUpdate,userMap);
            ycSysUserService.updateById(ycSysUserUpdate);

            //加保存日志
            String editUser = "修改用户信息: ";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldSysUser);
            editUser += LogUtils.BeanModifyMsg(ycSysUserUpdate,oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_SYS_USER,editUser,userId,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XG);

        }else{
            // 查询账号
            List<YcSysUser> userList = ycSysUserService.list(new LambdaQueryWrapper<YcSysUser>()
                    .eq(YcSysUser::getUsername, username));
            if (CollectionUtils.isNotEmpty(userList)){
                return HttpResult.error("账号【"+username+"】已存在");
            }else{
                //新增用户
                YcSysUser ycSysUser = new YcSysUser();
                BeanUtils.populate(ycSysUser,userMap);
                userId = GetUuIdUtils.ReplaceUuId();
                ycSysUser.setId(userId);
                ycSysUser.setPassword(SysUserConstant.PASSWORD);
                ycSysUser.setSalt(SysUserConstant.SALT);
                ycSysUser.setWorkNo(userId);
                ycSysUser.setIsRealUser(SysUserConstant.IS_REAL_USER);
                ycSysUser.setStatus(Integer.valueOf(SysUserConstant.STATUS));
                ycSysUser.setDelFlag(Integer.valueOf(SysUserConstant.DEL_FLAG));
                // 判断检查员、核查员
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    ycSysUser.setOrgId(SpcyConstant.HCY_ORGID); // 部门编号
                    ycSysUser.setOrgName(SpcyConstant.HCY_ORGNAME); // 部门名称
                    ycSysUser.setOrgCode(SpcyConstant.HCY_ORGCODE); // 默认机构编码
                }else {
                    ycSysUser.setOrgId(SpcyConstant.HCY_ZJ_ORGID); // 部门编号
                    ycSysUser.setOrgName(SpcyConstant.HCY_ZJ_ORGNAME); // 部门名称
                    ycSysUser.setOrgCode(SpcyConstant.HCY_ZJ_ORGCODE); // 默认机构编码
                }

                ycSysUserService.save(ycSysUser);

                // 新增日志
                String addSysUserOper = "新增用户：";
                Map<String, Object> addUserMap = ObjectToMapUtils.objectToMap(ycSysUser);
                addSysUserOper += LogUtils.MapToStringMethod(addUserMap);
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER,addSysUserOper,userId,LogConstant.LOGS_SYS_USER,SpcyConstant.LOGS_SYS_TYPE_XZ);

                // 新增部门用户关系
                YcSysUserDepart ycSysUserDepart = new YcSysUserDepart();
                ycSysUserDepart.setId(GetUuIdUtils.ReplaceUuId());
                ycSysUserDepart.setUserId(userId);

                // 判断核查员、专家
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    ycSysUserDepart.setDepId(SpcyConstant.HCY_ORGID); // 核查员部门编号
                }else {
                    ycSysUserDepart.setDepId(SpcyConstant.HCY_ZJ_ORGID); // 专家部门编号
                }

                ycSysUserDepart.setPositionId(""); // 职务编号
                ycSysUserDepart.setIsMajorDep(SysUserConstant.IS_MAJOR_DEP); // 是否主部门
                ycSysUserMapper.addYcSysUserDept(ycSysUserDepart);

                // 用户部门 日志
                String ycAddUserDepartOperCont = "新增系统用户部门联系：用户名["+ycSysUser.getRealname()+"]; 部门["+SpcyConstant.HCY_ORGNAME+"]; " +
                        "用户编号["+userId+"]; 部门编号["+SpcyConstant.HCY_ORGID+"];";
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_DEPT,ycAddUserDepartOperCont,userId,LogConstant.LOGS_SYS_USER_DEPT,SpcyConstant.LOGS_SYS_TYPE_XZ);

                String roleId = "";
                // 判断核查员、专家
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    roleId = SpcyConstant.getRoleIdByCode(fywflcode);
                }else {
                    roleId = SpcyConstant.getZjRoleIdByCode(fywflcode);
                }

                // 对用户角色进行自动授权
                YcSysUserRole userRole = new YcSysUserRole();
                userRole.setId(GetUuIdUtils.ReplaceUuId());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                ycSysUserMapper.addYcSysUserRole(userRole);

                // 加新增和授权的日志
                String ycAddUserRoleOperCont = "新增用户角色联系：用户名["+ycSysUser.getRealname()+"]; 用户编号["+userId+"]; " +
                        "角色编号["+roleId+"];]";
                spcyLogService.addLogs(LogConstant.LOGS_SYS_USER_ROLE,ycAddUserRoleOperCont,userId,LogConstant.LOGS_SYS_USER_ROLE,SpcyConstant.LOGS_SYS_TYPE_XZ);

            }

        }


        //处理核查员信息保存
        String hcyId = hcyMap.get("id");
        if(StringUtils.isNotBlank(hcyId) && StringUtils.isNotEmpty(hcyId)){
            //执行核查员信息更新
            SpcyRsHcy oldHcy = spcyRsHcyService.getById(hcyId);
            SpcyRsHcy hcyUpdate = spcyRsHcyService.getById(hcyId);
            BeanUtils.populate(hcyUpdate,hcyMap);
            spcyRsHcyService.updateById(hcyUpdate);

            //增加修改日志
            String editUser = "修改核查员信息: ";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(oldHcy);
            editUser += LogUtils.BeanModifyMsg(hcyUpdate,oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCY,editUser,userId,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XG);

        }else{
            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFuserid, userId)
                    .eq(SpcyRsHcy::getFywflcode, fywflcode)
            );
            if (CollectionUtils.isNotEmpty(hcyList)){
                return HttpResult.error("业务分类【"+fywflcode+"】+核查员【"+username+"】已存在");
            }else{
                SpcyRsHcy spcyRsHcy = new SpcyRsHcy();
                BeanUtils.populate(spcyRsHcy,hcyMap);
                spcyRsHcy.setId(GetUuIdUtils.ReplaceUuId());
                spcyRsHcy.setFuserid(userId);
                spcyRsHcyService.save(spcyRsHcy);

                //增加日志记录
                String addHcyOper = "新增核查员";
                Map<String, Object> addHcyMap = ObjectToMapUtils.objectToMap(spcyRsHcy);
                addHcyOper += LogUtils.MapToStringMethod(addHcyMap);
                spcyLogService.addLogs(LogConstant.LOGS_RS_HCY,addHcyOper,userId,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
        }

        return HttpResult.ok("修改成功");
    }

    /*@Log(title = "审评查验-核查员库-通过id删除")
    @ApiOperation(value = "审评查验-核查员库-通过id删除")
    @DeleteMapping(value = "/delete")*/
    public HttpResult<?> delete(@RequestParam("id") String id) {
        if (StringUtils.isEmpty(id)){
            return HttpResult.error("id参数不能为空");
        }
        SpcyRsHcy nowQy = spcyRsHcyService.getById(id);
        if (nowQy == null){
            return HttpResult.error("当前核查员库信息数据不存在，请重试");
        }
        String userid = nowQy.getFuserid();
        String fusertype = nowQy.getFusertype();
        String fywflcode = nowQy.getFywflcode();

        boolean flag = spcyRsHcyService.removeById(id);
        if (flag) {
            String roleId = "";
            // 判断核查员、专家
            if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                roleId = SpcyConstant.getRoleIdByCode(fywflcode);
            }else {
                roleId = SpcyConstant.getZjRoleIdByCode(fywflcode);
            }

            ycSysUserMapper.deleteUserRole(userid,roleId);

            String operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(nowQy);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCY, operContent, id, LogConstant.LOGS_RS_HCY, SpcyConstant.LOGS_SYS_TYPE_SC);
        }else {
            return HttpResult.error("删除核查员失败，请刷新重试并联系管理员");
        }

        return HttpResult.ok("删除成功");

    }

    /*@Log(title = "审评查验-核查员库-批量删除")
    @ApiOperation(value = "审评查验-核查员库-批量删除")
    @DeleteMapping(value = "/deleteBatch")*/
    public HttpResult<?> deleteBatch(@RequestParam("ids") String ids) {
        if (StringUtils.isEmpty(ids)){
            return HttpResult.error("ids参数不能为空");
        }
        List<String> idsList = Arrays.asList(ids.split(","));
        List<SpcyRsHcy> spcyRsHcyList = spcyRsHcyService.listByIds(idsList);
        if (CollectionUtils.isEmpty(spcyRsHcyList)){
            return HttpResult.error("数据不存在，请重试");
        }
        String operContent = "";
        for (SpcyRsHcy rsHcy : spcyRsHcyList){
            String id = rsHcy.getId();
            spcyRsHcyService.removeById(id);

            String userid = rsHcy.getFuserid();
            String fusertype = rsHcy.getFusertype();
            String fywflcode = rsHcy.getFywflcode();

            // 删除对应的角色关系
            if (StringUtils.isNotBlank(fywflcode)) {
                String roleId = "";
                // 判断核查员、专家
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    roleId = SpcyConstant.getRoleIdByCode(fywflcode);
                } else {
                    roleId = SpcyConstant.getZjRoleIdByCode(fywflcode);
                }
                ycSysUserMapper.deleteUserRole(userid, roleId);
            }

            operContent = "删除信息：";
            Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(rsHcy);
            operContent += LogUtils.MapToStringMethod(oldMap);
            spcyLogService.addLogs(LogConstant.LOGS_RS_HCY,operContent,id,LogConstant.LOGS_RS_HCY,SpcyConstant.LOGS_SYS_TYPE_SC);
            operContent = "";
        }

        return HttpResult.ok("删除成功");
    }

    /*@Log(title = "审评查验-核查员库-通过id查询")
    @ApiOperation(value = "审评查验-核查员库-通过id查询")
    @GetMapping(value = "/queryById")*/
    public HttpResult<?> queryById(@RequestParam("id") String id) {
        RsHcyVo hcyVo = new RsHcyVo();
        hcyVo.setId(id);
        List<RsHcyVo> rsHcyList = spcyRsHcyService.getRsHcyList(hcyVo);
        if (CollectionUtils.isNotEmpty(rsHcyList)){
            return HttpResult.ok(rsHcyList.get(0));
        }
        return HttpResult.ok("");
    }

    @Log(title = "选择中心人员 - 变成/专家 / 检查员 / 评审员")
    @ApiOperation(value = "选择中心人员 - 变成/专家 / 检查员 / 评审员")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "用户ids,多个用户用英文逗号,分割"),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码，如（001002 / 002等）"),
            @ApiImplicitParam(name = "fusertype",value = "选择所属人员库，如（检查员 / 专家）")
    })
    @PostMapping(value = "selectAddUserToHcy")
    public HttpResult<?> selectAddUserToHcy(@RequestBody HashMap<String,String> map){
        String ids = map.get("ids");
        String fywflcode = map.get("fywflcode");
        String fusertype = map.get("fusertype");

        if (StringUtils.isBlank(ids)){
            return HttpResult.error("请选择人员");
        }
        List<String> userIds = Arrays.asList(ids.split(",|，"));
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("请选择科室分类");
        }
        if (StringUtils.isBlank(fusertype)){
            return HttpResult.error("请选择人员分类");
        }
//        YcSysUser user = ycSysUserService.getById(ids);
//        if (user == null){
//            return HttpResult.error("当前人员不存在，请刷新重试");
//        }
        List<YcSysUser> sysUserList = ycSysUserService.listByIds(userIds);
        String deptName = SpcyConstant.getYwclNameByCode(fywflcode);

        int i = 0;
        for (String userId : userIds) {
            YcSysUser user = sysUserList.get(i);
            List<SpcyRsHcy> hcyList = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFuserid, userId)
                    .eq(SpcyRsHcy::getFywflcode, fywflcode)
                    .eq(SpcyRsHcy::getFusertype, fusertype)
            );

            if (CollectionUtils.isNotEmpty(hcyList)) {
                StringBuffer msg = new StringBuffer("当前人员");
                msg.append("[").append(user.getRealname()).append("]").append("已经存在[").append(deptName).append("]的[").append(fusertype).append("]库中。");
//            return HttpResult.error(msg.toString());
                log.error("选择人员出现：{}",msg.toString());
            } else {
                SpcyRsHcy spcyRsHcy = new SpcyRsHcy();
                spcyRsHcy.setId(GetUuIdUtils.ReplaceUuId());
                spcyRsHcy.setFuserid(userId);
                spcyRsHcy.setFywflcode(fywflcode);
                spcyRsHcy.setFusertype(fusertype);
                spcyRsHcy.setFssk(SpcyConstant.HCY_SSK_ZYK);
                spcyRsHcyService.save(spcyRsHcy);

                String roleId = "";
                if (fusertype.equals(SpcyConstant.HCY_USERTYPE_JCY)) {
                    roleId = SpcyConstant.getRoleIdByCode(fywflcode);
                }else {
                    roleId = SpcyConstant.getZjRoleIdByCode(fywflcode);
                }

                // 对用户角色进行自动授权
                YcSysUserRole userRole = new YcSysUserRole();
                userRole.setId(GetUuIdUtils.ReplaceUuId());
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                ycSysUserMapper.addYcSysUserRole(userRole);

                //增加日志记录
                String addHcyOper = "新增核查员";
                Map<String, Object> addHcyMap = ObjectToMapUtils.objectToMap(spcyRsHcy);
                addHcyOper += LogUtils.MapToStringMethod(addHcyMap);
                spcyLogService.addLogs(LogConstant.LOGS_RS_HCY, addHcyOper, userId, LogConstant.LOGS_RS_HCY, SpcyConstant.LOGS_SYS_TYPE_XZ);
            }
            i++;
        }

//        StringBuffer msg = new StringBuffer("添加成功，当前人员");
//        msg.append("[").append(user.getRealname()).append("]").append("添加到[").append(deptName).append("]的[").append(fusertype).append("]库中。");
//        return HttpResult.ok(msg.toString());
        return HttpResult.ok("选择成功");
    }

    /*@Log(title = "导入核查员数据-表格excel")
    @ApiOperation(value = "导入核查员数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "file",value = "excel模板文件",required = true),
            @ApiImplicitParam(name = "fywflcode",value = "业务分类编码",required = true)
    })
    @PostMapping(value = "impRsHcyData")*/
    public HttpResult<?> impRsHcyData(@RequestParam("file") MultipartFile file,@RequestParam("fywflcode")String ywflCode){
        if (file.isEmpty()){
            return HttpResult.error("文件不存在");
        }

        //获取文件名
        String fileName = file.getOriginalFilename();
        //判断文件类型，这里我们只要xls文件
        if (fileName != null && !fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))
            return HttpResult.error(1, "请选择“xls”或“xlsx”文件");

        File fileUpload = localFileUploadUtils.uploadDempFile(file,fileName);
        // 获取导入的数据
        List<Map<String, Object>> mapsList = null;
        try {
            mapsList = myExcelUtils.paresExclToMapList(BusinessConstant.IMPORT_RS_HCY_XML, fileUpload);
        } catch (Exception e) {
            log.error("导入检查员数据出错-{}",e.getMessage());
        }
        if (CollectionUtils.isNotEmpty(mapsList) && mapsList.size() > 0) {
            int xh = 0;
            for (Map map : mapsList) {
                xh = xh + 1;
                spcyRsHcyService.impRsHcyData(map,ywflCode,xh);
            }
        }
        fileUpload.delete();
        return HttpResult.ok("导入成功");
    }

    /*@Log(title = "下载核查员员-导入模板")
    @ApiOperation(value = "下载检查员-导入模板")
    @GetMapping("/downRsHcyTemplate")*/
    public void downRsHcyTemplate(HttpServletResponse response){
        try {
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode("hcyImpTemplate.xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();
            myExcelUtils.buildImpModel(BusinessConstant.IMPORT_RS_HCY_XML, out);
        } catch (Exception e) {
            log.error("下载检查员模板错误-{}",e.getMessage());
        }
    }

    /*@Log(title = "导出核查员数据-表格excel")
    @ApiOperation(value = "导出核查员数据-表格excel")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "ids",value = "核查员id字符逗号分割",dataType = "String")
    })
    @PostMapping("/exportRsHcyData")*/
    public void exportRsHcyData(@RequestParam(value = "ids",defaultValue = "")String ids,
                                @RequestBody RsHcyVo rsHcyVo,
                                HttpServletResponse response){
        try {
            String name = "exportRsHcy";
            response.setContentType("application/ms-excel;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(name+".xls", "UTF-8"))));
            OutputStream out = response.getOutputStream();

            List<String> IdsList = Arrays.asList(ids.split(","));
            List<Object> list = new ArrayList<>(); // 导出的数据
            // 多选导出
            if (StringUtils.isNotEmpty(ids)) {
                RsHcyVo hcyListVo = null;
                for (String id : IdsList) {
                    hcyListVo = new RsHcyVo();
                    hcyListVo.setId(id);
                    List<RsHcyVo> rsHcyList = spcyRsHcyService.getRsHcyList(hcyListVo);
                    if (CollectionUtils.isNotEmpty(rsHcyList)) {
                        list.add(rsHcyList.get(0));
                    }
                }
            }else {
                // 条件导出
                List<RsHcyVo> rsHcyList = spcyRsHcyService.getRsHcyList(rsHcyVo);
                for (RsHcyVo e : rsHcyList){
                    list.add(e);
                }
            }
            myExcelUtils.outputListToExclFile(BusinessConstant.IMPORT_RS_HCY_XML,list,out); // 导出模板数据成excel
        } catch (Exception e) {
            log.error("导出核查员数据出错-{}",e.getMessage());
        }
    }
}
